package com.example.javaow.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.javaow.domain.base.PageResult;
import com.example.javaow.domain.base.ResponseResult;
import com.example.javaow.domain.entity.DeviceCommandLog;
import com.example.javaow.service.DeviceCommandLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 指令发送日志控制器
 */
@RestController
@RequestMapping("/command")
@RequiredArgsConstructor
@Slf4j
public class DeviceCommandLogController {
    
    @Autowired
    private DeviceCommandLogService deviceCommandLogService;
    
    /**
     * 分页查询指令发送日志
     * @param pageNum 当前页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @param groupAddress 分组地址
     * @param deviceAddress 设备地址
     * @return 分页结果
     */
    @GetMapping("/list")
    public ResponseResult<PageResult<DeviceCommandLog>> list(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "100") int pageSize,
            @RequestParam(value = "groupAddress", required = false) Integer groupAddress,
            @RequestParam(value = "deviceAddress", required = false) Integer deviceAddress) {

        IPage<DeviceCommandLog> page = deviceCommandLogService.getByConditions(
                pageNum, pageSize, groupAddress, deviceAddress);
        PageResult<DeviceCommandLog> result = new PageResult<>();
        result.setTotal(page.getTotal());
        result.setPages((int) page.getPages());
        result.setCurrent((int) page.getCurrent());
        result.setSize((int) page.getSize());
        result.setRecords(page.getRecords());
        return ResponseResult.success("查询成功", result);
    }
    
    /**
     * 新增指令发送日志
     * @param deviceCommandLog 指令发送日志实体
     * @return 操作结果
     */
    @PostMapping
    public ResponseResult addDeviceCommandLog(@RequestBody DeviceCommandLog deviceCommandLog) {
        log.info("新增指令发送日志：{}", deviceCommandLog);
        boolean result = deviceCommandLogService.addDeviceCommandLog(deviceCommandLog);
        if (result) {
            return ResponseResult.success("新增成功");
        } else {
            return ResponseResult.error("新增失败");
        }
    }
}
